package com.young.jdbc;

import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

/**
 * @Author: young
 * @Date: 2021-12-03 8:31
 * @Description: 演示PreparedStatement（预处理）的使用
 * 好处：
 * 1. 不再使用+拼接SQL语句，减少语法错误
 * 2. 有效解决了SQL注入的问题
 * 3. 大大减少了编译次数，效率更高
 */
public class PreparedStatement_demo {
    public static void main(String[] args) throws Exception {
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入管理员名称：");
        String admin_name = scanner.nextLine();
        System.out.println("请输入管理员密码：");
        String admin_pwd = scanner.nextLine();

        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driver = properties.getProperty("driver");

        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, password);

        String sql = "select name,pwd from admin where name=? and pwd=?";
        // preparedStatement对象实现了PreparedStatement接口的实现类的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,admin_name);
        preparedStatement.setString(2,admin_pwd);
        // 这里执行executeQuery，不用再写sql
        ResultSet resultSet = preparedStatement.executeQuery();

        if (resultSet.next()){
            System.out.println("恭喜，登陆成功");
        }else {
            System.out.println("对不起，登陆失败");
        }

        resultSet.close();
        preparedStatement.close();
        connection.close();

    }
}
